/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db.server.Connection;

import db.server.DTO.DatabaseDTO;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author QuangKhai
 */
public class DBServerListener implements Runnable{
    private Socket socket;
    private ServerSocket serSocket;
    private String username;
    private String password;       
    private Thread server = new Thread();
    private List<DatabaseDTO> databaseDTO = new ArrayList<DatabaseDTO>();
    
    public DBServerListener(String address, int port, String username, String password, List<DatabaseDTO> databaseDTO) throws IOException{
        this.serSocket = new ServerSocket();
        this.serSocket.bind(new InetSocketAddress(address, port));     
        this.username = username;
        this.password = password;                 
        this.databaseDTO = databaseDTO;
    }
    
    public void setConnection() throws IOException{
        while(true){
            this.socket = serSocket.accept();            
            
            if(server.isAlive()){                
                int confirm = JOptionPane.showConfirmDialog(null, "Another client want to connect");
                if(confirm == JOptionPane.YES_OPTION) {
                    server.suspend();
                    server = new Thread(new DBServerTrans(socket, username, password, databaseDTO));
                    server.start();          
                }                
            }else{                      
                server = new Thread(new DBServerTrans(socket, username, password, databaseDTO));
                server.start();                          
            }          
        }
    }
    
    @Override
    public void run() {
        try {
            setConnection();
        } catch (IOException ex) {
            Logger.getLogger(DBServerListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
